package com.xuanwei.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.xuanwei.core.cache.HomePageCache;
import com.xuanwei.core.entity.vo.ProductListVo;
import com.xuanwei.core.entity.param.Navigate;
import com.xuanwei.core.enums.NavigatePosition;
import com.xuanwei.core.exception.XwException;
import com.xuanwei.core.service.IXwHomepageNavigateService;
import com.xuanwei.core.service.IXwNavigateProductService;
import com.xuanwei.core.service.IXwProductService;
import com.xuanwei.dao.entity.XwHomepageNavigate;
import com.xuanwei.dao.entity.XwNavigateProduct;
import com.xuanwei.dao.entity.XwProduct;
import com.xuanwei.dao.mapper.XwHomepageNavigateMapper;
import com.xuanwei.xwcommon.util.BeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 首页导航 服务实现类
 * </p>
 *
 * @author mjy
 * @since 2019-07-30
 */
@Service
public class XwHomepageNavigateServiceImpl extends ServiceImpl<XwHomepageNavigateMapper, XwHomepageNavigate> implements IXwHomepageNavigateService {

    private IXwNavigateProductService navigateProductService;

    private IXwProductService productService;



    public XwHomepageNavigateServiceImpl(IXwNavigateProductService navigateProductService,
                                         IXwProductService productService
                                      ) {
        this.navigateProductService = navigateProductService;
        this.productService = productService;
    }

    @Override
    public void addOrUpdate(Navigate navigate) {
        XwHomepageNavigate byName = findByName(navigate.getName());
        if (navigate.getId() == null) {
            if (byName != null) {
                throw new XwException("该名称已存在");
            }
            if (navigate.getPosition() != NavigatePosition.ACTIVITY.getCode()) {
                int count = count(new QueryWrapper<XwHomepageNavigate>().eq("position", navigate.getPosition()));
                if (count == 1) {
                    throw new XwException("已存在该导航");
                }
            }

            XwHomepageNavigate homepageNavigate = new XwHomepageNavigate();
            BeanUtils.copyProperties(navigate, homepageNavigate);
            homepageNavigate.setUpdateTime(LocalDateTime.now());
            homepageNavigate.setCreateTime(LocalDateTime.now());
            save(homepageNavigate);
        } else {
            XwHomepageNavigate homepageNavigate = getById(navigate.getId());
            if (homepageNavigate == null) {
                throw new XwException("该数据不存在");
            }
            if (byName != null && byName.getId() != navigate.getId()) {
                throw new XwException("该名称已存在");
            }
            navigate.setPosition(null);
            BeanUtils.copyProperties(navigate, homepageNavigate);
            homepageNavigate.setUpdateTime(LocalDateTime.now());
            updateById(homepageNavigate);
        }
    }

    private XwHomepageNavigate findByName(String name) {
        return getOne(new QueryWrapper<XwHomepageNavigate>()
                .select("id,`name`")
                .eq("`name`", name));
    }

    @Override
    public void changeStatus(Integer id) {
        XwHomepageNavigate homepageNavigate = getById(id);
        if (homepageNavigate == null) {
            throw new XwException("数据不存在");
        }
        homepageNavigate.setShowStatus(homepageNavigate.getShowStatus() == 0 ? 1 : 0);
        homepageNavigate.setUpdateTime(LocalDateTime.now());
        updateById(homepageNavigate);
    }

    @Override
    public List<XwHomepageNavigate> all() {
        return list();
    }

    @Override
    public void delete(Integer id) {
        baseMapper.deleteById(id);
    }

    @Override
    public List<Navigate> showList() {
        List<XwHomepageNavigate> list = list(new QueryWrapper<XwHomepageNavigate>()
                .eq("show_status", 0));
        return BeanUtil.copyList(list, Navigate.class);
    }

    @Override
    public void addProductToNavigate(Integer id, List<Integer> productIds) {
        int count = navigateProductService.count(new QueryWrapper<XwNavigateProduct>().eq("navigate_id", id));

        //TODO 导航位置10个商品
        if ((10 - count) < productIds.size()) {
            throw new XwException("每个导航位置只能10个商品");
        }
        productIds.forEach(s -> {
            XwNavigateProduct one = navigateProductService.getOne(new QueryWrapper<XwNavigateProduct>()
                    .select("id").eq("product_id", s).eq("navigate_id", id));
            if (one != null) {
                throw new XwException("[id:" + s + "]已存在该导航里");
            }
            XwNavigateProduct navigateProduct = new XwNavigateProduct();
            XwProduct product = productService.getOne(new QueryWrapper<XwProduct>().select("id")
                    .eq("id", s).eq("`status`", 0));
            if (product == null) {
                throw new XwException("[id:" + s + "]该商品不存在");
            }
            navigateProduct.setNavigateId(id);
            navigateProduct.setProductId(s);
            navigateProductService.save(navigateProduct);
        });
    }

    @Override
    public List<ProductListVo> findProductById(Integer id) {
        List<XwNavigateProduct> list = navigateProductService.list(new QueryWrapper<XwNavigateProduct>()
                .eq("navigate_id", id));

        List<ProductListVo> productListVos = Lists.newArrayListWithCapacity(list.size());
        list.forEach(s -> {
            ProductListVo productListVo = new ProductListVo();
            Integer productId = s.getProductId();
            XwProduct product = productService.getOne(new QueryWrapper<XwProduct>()
                    .select("`name`,main_image,price,`status`").eq("id", productId));
            BeanUtils.copyProperties(product, productListVo);
            productListVo.setId(s.getId());
            productListVos.add(productListVo);
        });
        return productListVos;
    }

    @Override
    public void removeProduct(Integer id) {
        navigateProductService.getBaseMapper().deleteById(id);
    }

    @Override
    public Page<ProductListVo> searchProductList(Integer id, Integer productId, String name, Page<XwProduct> page) {
        List<XwNavigateProduct> list = navigateProductService.list(new QueryWrapper<XwNavigateProduct>()
                .select("product_id").eq("navigate_id", id));
        List<Integer> ids = list.stream().map(XwNavigateProduct::getProductId).collect(Collectors.toList());
        QueryWrapper<XwProduct> queryWrapper = new QueryWrapper<>();
        if (productId != null) {
            queryWrapper.eq("id", productId);
        }
        if (!StringUtils.isEmpty(name)) {
            queryWrapper.like("`name`", name);
        }
        if (ids.size() != 0) {
            queryWrapper.notIn("id", ids);
        }
        queryWrapper.eq("status", 0);
        queryWrapper.select("id,`name`,main_image,price,stock,create_time");
        productService.page(page, queryWrapper);
        List<XwProduct> records = page.getRecords();
        List<ProductListVo> productListVos = BeanUtil.copyList(records, ProductListVo.class);
        Page<ProductListVo> pageData = new Page<>(page.getCurrent(), page.getSize());
        pageData.setTotal(page.getTotal());
        pageData.setPages(page.getPages());
        pageData.setRecords(productListVos);
        return pageData;
    }

    @Override
    public boolean isExist(Integer productId, Integer activityId) {

        XwHomepageNavigate one = getOne(new QueryWrapper<XwHomepageNavigate>()
                .select("id")
                .eq("id", activityId)
                .eq("position", NavigatePosition.ACTIVITY.getCode()));
        if (one == null) {
            throw new XwException("该活动不存在");
        }

        XwNavigateProduct navigateProduct = navigateProductService.getOne(new QueryWrapper<XwNavigateProduct>()
                .select("id").eq("navigate_id", activityId)
                .eq("product_id", productId));

        return navigateProduct != null;
    }
}
